import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 主题上下文类型定义
interface ThemeContextType {
  isDarkMode: boolean;
  toggleTheme: () => void;
}

// 创建上下文
const ThemeContext = createContext<ThemeContextType>({
  isDarkMode: false,
  toggleTheme: () => {},
});

// 主题提供者组件
interface ThemeProviderProps {
  children: ReactNode;
}

export function ThemeProvider({ children }: ThemeProviderProps) {
  const [isDarkMode, setIsDarkMode] = useState(false);
  
  // 在应用启动时加载保存的主题设置
  useEffect(() => {
    const loadThemePreference = async () => {
      try {
        const savedTheme = await AsyncStorage.getItem('theme_preference');
        if (savedTheme !== null) {
          setIsDarkMode(savedTheme === 'dark');
        }
      } catch (error) {
        console.log('加载主题偏好设置失败:', error);
      }
    };
    
    loadThemePreference();
  }, []);
  
  // 切换主题并保存设置
  const toggleTheme = async () => {
    const newThemeValue = !isDarkMode;
    setIsDarkMode(newThemeValue);
    
    // 保存主题偏好设置
    try {
      await AsyncStorage.setItem('theme_preference', newThemeValue ? 'dark' : 'light');
    } catch (error) {
      console.log('保存主题偏好设置失败:', error);
    }
  };
  
  const value = {
    isDarkMode,
    toggleTheme
  };
  
  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

// 自定义Hook，用于在组件中使用主题
export const useTheme = () => useContext(ThemeContext);

export default ThemeContext; 